<template>
	<view class="container">
		<view class="personal">
			<!-- 页面头部 -->
			<view class="header">
				<view class="title">
					<text>获取您的昵称、头像</text>
				</view>
				<view class="sub-title">
					<text>填写您的微信头像和昵称，以便获得更好的体验</text>
				</view>
			</view>
			<!-- 表单组件 -->
			<view class="login-form">
				<view class="form-item">
					<view class="form-item--label">头像</view>
					<button class="btn-normal" style="flex: 1;" open-type="chooseAvatar" @click="onClickAvatar()"
						@chooseavatar="onChooseAvatar">
						<avatar-image v-if="avatarUrl" :url="avatarUrl" :width="100" />
						<text v-else style="color: #c0c4cc;font-size: 28rpx;">请选择头像</text>
					</button>
				</view>
				<view class="form-item">
					<view class="form-item--label">昵称</view>
					<input class="form-item--input" type="nickname" v-model="form.nickName" maxlength="30"
						placeholder="请输入微信昵称" placeholder-style="color: #c0c4cc;" @input="onInputNickName"
						@blur="onInputNickName" />
				</view>
			</view>
			<!-- 操作按钮 -->
			<view v-if="isGetPhone" class="login-btn">
				<button class="button" :class="{ disabled }" open-type="getPhoneNumber"
					@getphonenumber="handelMpWeixinMobileLogin($event)">确认</button>
			</view>
			<view v-else class="login-btn">
				<view class="button" :class="{ disabled }" @click="handleSubmit()">确认</view>
			</view>
			<!-- <view class="no-login-btn">
				<view class="button" @click="handleCancel()">暂不登录</view>
			</view> -->
		</view>
		<u-toast ref="uToast1" />
	</view>
</template>

<script>
	import store from '@/store';
	import * as LoginApi from '@/api/login';
	import * as UploadApi from '@/api/upload';
	import * as UserApi from '@/api/user';
	import {
		isEmpty
	} from '@/utils/util'
	import * as Verify from '@/utils/verify';
	import AvatarImage from '@/components/avatar-image';
	import StorageUtils from "@/utils/StorageUtils";
	import WXUtils from "@/utils/WXUtils.js";
	import UserService from '@/service/UserService';
	import {
		showInfo
	} from '@/utils/ToastUtils';
	import CacheConfig from '@/config/CacheConfig';

	export default {
		components: {
			AvatarImage
		},
		data() {
			return {
				disabled: false,
				// 头像路径 (用于显示)
				avatarUrl: '',
				// 临时图片 (用于上传)
				tempFile: undefined,
				// 表单数据
				form: {
					avatarUrl: null,
					nickName: '',
					code: '',
					loginCode: '',
					encryptedData: '',
					iv: '',
				},
				isClear: true,
			}
		},
		computed: {
			isGetPhone() {
				const app = this;
				return !Verify.isEmpty(app.form.nickName) && (app.tempFile || app.form.avatarUrl);
			}
		},
		created() {

		},
		onUnload() {
			if(this.isClear) {
				console.log("onUnload onUnload onUnload onUnload onUnload");
				StorageUtils.clear();
			}
		},
		methods: {
			// 获取code
			// 绑定昵称输入框 (用于微信小程序端快速填写昵称能力)
			onInputNickName({
				detail
			}) {
				// console.log(detail)
				if (detail.value) {
					this.form.nickName = detail.value
				}
			},
			// 点击头像按钮事件
			onClickAvatar() {
				// #ifdef MP-WEIXIN
				return
				// #endif
				this.chooseImage()
			},
			// 选择头像事件 - 仅限微信小程序
			onChooseAvatar({
				detail
			}) {
				// #ifdef MP-WEIXIN
				const app = this;
				app.avatarUrl = detail.avatarUrl;
				console.log("app.avatarUrl", app.avatarUrl);
				app.tempFile = {
					path: app.avatarUrl
				}
				// #endif
			},
			// 选择图片
			chooseImage() {
				const app = this
				// 选择图片
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success({
						tempFiles
					}) {
						app.tempFile = tempFiles[0]
						app.avatarUrl = app.tempFile.path
					}
				});
			},
			// 上传图片
			uploadFile() {
				const app = this
				return UploadApi.image([app.tempFile])
					.then(fileIds => {
						console.log("fileIds", fileIds);
						app.form.avatarUrl = "https://" + fileIds;
						app.tempFile = null;
						return true;
					})
					.catch(() => {
						return false;
					})
			},
			async handleSubmit() {
				const app = this;
				console.log('handleSubmit', app.form, app.tempFile)
				if (app.disabled === true) {
					return;
				}
				if (app.tempFile === undefined || Verify.isEmpty(app.form.nickName)) {
					app.$toast('请填写头像和昵称~');
					return;
				}
				// 按钮禁用
				app.disabled = true;
				// 先上传头像图片
				if (app.tempFile && !await app.uploadFile()) {
					app.$toast('很抱歉，头像上传失败');
					app.disabled = false;
					return;
				}
			},
			handleCancel() {},
			async handelMpWeixinMobileLogin({
				detail
			}) {
				const app = this;
				console.log("detail", detail);
				app.disabled = true;
				if (detail.errMsg != 'getPhoneNumber:ok') {
					console.log('微信授权获取手机号失败', detail);
					app.disabled = false;
					return;
				}
				if (detail.errMsg == 'getPhoneNumber:ok') {
					const loginRes = await UserService.wxLogin();
					if (!loginRes) {
						return;
					}
					// 获取手机号
					this.form.code = detail.code;
					this.form.encryptedData = detail.encryptedData;
					this.form.iv = detail.iv;
					const {
						code
					} = await WXUtils.login();
					console.log("code", code);
					this.form.loginCode = code;

					if (app.tempFile && !await app.uploadFile()) {
						app.$toast('很抱歉，头像上传失败');
						app.disabled = false;
						return;
					}
					const param = {
						...app.form,
						clientId: UserService.userInfo.clientId,
						appid: "wx9defdd2125f88fbb"
					};
					console.log("updateUserInfo param", param);
					UserApi.updateUserInfo(param).then(res => {
						console.log("updateUserInfo res", res);
						console.log("UserService", UserService.userInfo);
						app.$toast("注册成功");
						app.disabled = false;
						let isReLogin = false;
						let uuid = UserService.userInfo.uuid;
						this.getUserInfoByUuid(uuid);
					}).catch(err => {
						console.log("updateUserInfo error", err);
						app.disabled = false;
					})
				}
			},
			getUserInfoByUuid(uuid) {
				UserApi.getUserIdByUuid(uuid).then(result => {
					console.log("getUserIdByUuid result", result);
					const userInfo = result.obj;
					const {
						avatarUrl,
						nickName,
						weight,
						height,
						gender,
						birth,
						mobile
					} = userInfo;
					console.log("userInfo", userInfo);
					this.isClear = false;
					if (weight == null || height == null || gender == null || birth == null || mobile == null) {
						uni.redirectTo({
							url: '/pages/mine/personal'
						})
					} else {
						uni.reLaunch({
							url: '/pages/oxygen/index'
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 0 60rpx;
		font-size: 32rpx;
		background: #fff;
		min-height: 100vh;
	}

	.personal {

		// 页面头部
		.header {
			padding-top: 120rpx;
			margin-bottom: 60rpx;

			.title {
				margin-bottom: 20rpx;
				color: #191919;
				font-size: 44rpx;
			}

			.sub-title {
				margin-bottom: 70rpx;
				color: #b3b3b3;
				font-size: 28rpx;
			}
		}

		.login-form {
			margin-bottom: 90rpx;
		}

		// 输入框元素
		.form-item {
			display: flex;
			align-items: center;
			padding: 18rpx;
			border-bottom: 1rpx solid #f3f1f2;
			margin-bottom: 30rpx;
			min-height: 96rpx;

			&--label {
				min-width: 150rpx;
				font-size: 28rpx;
				line-height: 50rpx;
			}

			&--input {
				font-size: 28rpx;
				letter-spacing: 1rpx;
				flex: 1;
				height: 100%;
			}

			&--parts {
				min-width: 100rpx;
			}
		}

	}

	.login-btn {
		margin-bottom: 20rpx;

		.button {
			width: 100%;
			height: 86rpx;
			// background: #0dd30c;
			background-color: #F08801;
			color: #fff;
			font-size: 30rpx;
			border-radius: 80rpx;
			letter-spacing: 5rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			// 禁用按钮
			&.disabled {
				opacity: 0.6;
			}
		}
	}


	.no-login-btn {

		.button {
			height: 86rpx;
			background: #dfdfdf;
			color: #fff;
			font-size: 30rpx;
			border-radius: 80rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>